/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import Utility.RoyalLogger;
import constants.CommonConstants;
import java.io.IOException;
import java.util.List;
import logging.CommonsLogging;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.PropertyConfigurator;
import org.eclipse.persistence.internal.sessions.factories.model.property.PropertyConfig;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import vo.rb_users;

/**
 *
 * @author Shuhail
 */
public class rb_users_persist {
  
    
    

    Session sess=null;
    Transaction tx=null;
    Logger logger = CommonsLogging.getInstance().getLogger();
    public rb_users_persist() {
    
        SessionFactory sf=new Configuration().configure().buildSessionFactory();
        sess=sf.openSession();
        tx=sess.beginTransaction();
    }
    
    public static rb_users_persist getInstance() {
        return new rb_users_persist();
    }
    
    public void insert(rb_users u) {
        try {
        tx.begin();
        rb_users users=new rb_users();
        users.setUser_name(u.getUser_name());
        users.setPassword(u.getPassword());
        users.setRole(u.getRole());
        sess.save(users);
        tx.commit();}
        catch(Exception e) {
            tx.rollback();
        }
        
    }
    
    
    public rb_users fetch(rb_users u) {
        
        tx.begin();
        Query query=sess.getNamedQuery("getUserIdAndPassword");
        query.setString("user_name", u.getUser_name());
        query.setString("password", u.getPassword());
        
        List results=query.list();
        //Check whether He is a fraud
        if(results.size()==0) {
            u.setRole(CommonConstants.NOT_AUTHENTICATED_USER_FLAG);
            u.setUser_id(0);
            return u;
        }
       
        rb_users r=(rb_users)results.get(0);
        
        if(logger.isDebugEnabled()){
            logger.debug(r.getUser_name()+"****"+r.getRole());
        }
        return r;
    } 
    
    
    
    public boolean updatePassword(rb_users u,String new_password) throws IOException {
        
      
           u=this.fetch(u);
             if(u.getUser_id()==0) {
            return false;
        }
        u.setPassword(new_password);
        try {
            
            tx.begin();
            sess.update(u);
            tx.commit(); 
            
        }catch(Exception e) {
            
        }
        finally{
            System.out.println("=====Password Changed Successfully====");
            return true;
        }
       
    }
}
